package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jwdf.uda.R;
import com.jwdf.uda.databinding.ItemDropMenuAnswerBinding;
import com.jwdf.uda.databinding.LayFindCategoryBinding;
import com.jwdf.uda.databinding.ViewMenuListBinding;
import com.jwdf.uda.ui.adapter.AbsAdapter;
import com.jwdf.uda.ui.adapter.AbsViewHolder;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.find.index.FindDressFragment;
import com.jwdf.uda.ui.fragment.find.index.FindEmotionFragment;
import com.jwdf.uda.ui.fragment.find.index.FindLifeFragment;
import com.jwdf.uda.ui.fragment.find.index.FindMakeUpFragment;
import com.jwdf.uda.utils.DisplayUtils;

import java.util.ArrayList;
import java.util.List;

import static android.databinding.DataBindingUtil.bind;

/**
 * Created by RD-001 on 2016/4/27.
 */
public class FindCategoryActivity extends AbsActivity implements View.OnClickListener {

    public static final String TAG = FindCategoryActivity.class.getSimpleName();
    public static final String strCaregory = "category";
    public static final int DRESS = 0, MAKEUP = 1, LIFE = 2, EMOTION = 3;
    int posSel = 0;
    private RotateAnimation mRotateAnimation;
    private RotateAnimation mReverseAnimation;
    private PopupWindow mDropDownMenu;
    private int mRotateDuration = 150;
    private int menuWidth;
    private MenuItemAdapter mAdapter;
    private ImageView mArrowRotate;
    private LinearLayout mTileLayout;
    private TextView tvTitle;
    private LayFindCategoryBinding mDataBinding;
    public static FindCategoryActivity instance() {
        FindCategoryActivity view = new FindCategoryActivity();
        return view;
    }
    public static void start(Context context, int category) {
        Intent intent = new Intent(context, FindCategoryActivity.class);
        intent.putExtra(strCaregory, category);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataBinding = DataBindingUtil.setContentView(this,R.layout.lay_find_category);
        setupContentView();
    }

    @Override
    protected boolean fullScreenMode() {
        return true;
    }

    private void setupContentView() {
        createAnimation();

        LinearLayout.LayoutParams flParams = (LinearLayout.LayoutParams) mDataBinding.rlCategory.getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(this);
        mDataBinding.rlCategory.setLayoutParams(flParams);
        mDataBinding.llFilterTitle.setPadding(0, DisplayUtils.getStatusBarHeight(this), 0, 0);
        mDataBinding.flHeadAction.setPadding(DisplayUtils.dipToPix(this,15), DisplayUtils.getStatusBarHeight(this), DisplayUtils.dipToPix(this,15), 0);
        mDataBinding.flHeadBack.setPadding(DisplayUtils.dipToPix(this,15), DisplayUtils.getStatusBarHeight(this), DisplayUtils.dipToPix(this,15), 0);

        mArrowRotate = (ImageView) findViewById(R.id.iv_arrow_rotate);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        mTileLayout = (LinearLayout) findViewById(R.id.ll_filter_title);

        mTileLayout.setOnClickListener(createOnClickListener());
        findViewById(R.id.fl_head_back).setOnClickListener(createOnClickListener());
        findViewById(R.id.fl_head_action).setOnClickListener(createOnClickListener());

        listAdd();

    }

    private void listAdd() {

        final ArrayList<BaseFragment> listFrag = new ArrayList<>();

        listFrag.add(new FindDressFragment());
        listFrag.add(new FindMakeUpFragment());
        listFrag.add(new FindLifeFragment());
//        listFrag.add(new FindShoppingFragment());
        listFrag.add(new FindEmotionFragment());
        listFrag.trimToSize();

        final int pos = getIntent().getIntExtra(strCaregory, -1);
        tvTitle.setText(listFrag.get(pos).getTitle());
        final FragmentManager fm = getSupportFragmentManager();
        final int canFrag = R.id.layFrag;

        fm.beginTransaction().replace(canFrag, listFrag.get(pos)).commit();

        final List<String> listStr = new ArrayList<>(listFrag.size());
        for(BaseFragment item : listFrag)
            listStr.add(item.getTitle());

        View menuView = getLayoutInflater().inflate(R.layout.view_menu_list, null);

        final ViewMenuListBinding menuListBinding = bind(menuView);

        mAdapter = new MenuItemAdapter(this);
        final ListView lv = menuListBinding.menuList;

        lv.setBackgroundResource(R.drawable.pop_quiz_original);

        lv.setAdapter(mAdapter);

        mAdapter.setData(listStr);
        mAdapter.setOnMenuItemSelectedListener(new MenuItemAdapter.OnMenuItemSelectedListener() {
            @Override
            public void onMenuItemSelected(String item, int position) {
                mDropDownMenu.dismiss();

//                if(posSel != position) {
                    tvTitle.setText(listStr.get(position));

                    final FragmentTransaction transaction = fm.beginTransaction();
                    final BaseFragment fragment = listFrag.get(position);
//                    if(fragment.isAdded()) {
//                        transaction.show(fragment).commit();
//                    }
//                    else {
                        transaction.replace(canFrag, fragment).commit();
//                    }

                    lv.getChildAt(posSel).findViewById(R.id.tv).setSelected(false);
                    lv.getChildAt(position).findViewById(R.id.tv).setSelected(true);

                    posSel = position;
//                    EventBusUtil.post(new FilterListEvent(position));
//                }
            }
        });

        mDropDownMenu = new PopupWindow(menuView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mDropDownMenu.setFocusable(true);
        mDropDownMenu.setOutsideTouchable(true);
        mDropDownMenu.setBackgroundDrawable(new BitmapDrawable());
        mDropDownMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mArrowRotate.clearAnimation();
                mArrowRotate.startAnimation(mReverseAnimation);
            }
        });

        menuView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        menuWidth = menuView.getMeasuredWidth();
    }

    private void createAnimation() {
        mRotateAnimation = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mRotateAnimation.setInterpolator(new LinearInterpolator());
        mRotateAnimation.setDuration(mRotateDuration);
        mRotateAnimation.setFillAfter(true);

        mReverseAnimation = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mReverseAnimation.setInterpolator(new LinearInterpolator());
        mReverseAnimation.setDuration(mRotateDuration);
        mReverseAnimation.setFillAfter(true);
    }

    private View.OnClickListener createOnClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int viewId = v.getId();
                if(R.id.fl_head_back == viewId) {
                    finish();
                } else if(R.id.ll_filter_title == viewId) {
                    showDropDownMenu();
                } else if(R.id.fl_head_action == viewId) {
                    startActivity(new Intent(FindCategoryActivity.this, NewProblemsActivity.class));
                }
            }
        };
    }

    private void showDropDownMenu() {
        if(mAdapter.getCount() == 0) {
            return;
        }
        mArrowRotate.clearAnimation();
        mArrowRotate.startAnimation(mRotateAnimation);
        int xOff = (mTileLayout.getWidth() - menuWidth) / 2;
        mDropDownMenu.showAsDropDown(mTileLayout, xOff, 0);
    }

    public static class MenuItemAdapter extends AbsAdapter<String> {

        private OnMenuItemSelectedListener mListener;

        public MenuItemAdapter(Context context) {
            super(context);
        }

        public void setOnMenuItemSelectedListener(OnMenuItemSelectedListener listener) {
            this.mListener = listener;
        }

        @Override
        protected AbsViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
            return new MenuItemViewHolder(mInflater.inflate(R.layout.item_drop_menu_answer, parent, false));
        }

        public interface OnMenuItemSelectedListener {
            void onMenuItemSelected(String item, int position);
        }
        public class MenuItemViewHolder extends AbsViewHolder<String> {
            private ItemDropMenuAnswerBinding mBinding;

            public MenuItemViewHolder(View convertView) {
                super(convertView);
                mBinding = bind(convertView);
            }

            @Override
            protected void onBindView(String item, final int position) {
                if(position == 0)
                    mBinding.divider.setVisibility(View.GONE);
                mBinding.tv.setText(item);

                mBinding.menuItemView.setTag(R.id.tag, item);
                mBinding.menuItemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(mListener != null) {
                            mListener.onMenuItemSelected((String) v.getTag(R.id.tag), position);
                        }
                    }
                });
            }
            @Override
            protected void onBindView(String item) {

            }
        }
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.fl_head_back:
                onBackPressed();
                break;

            case R.id.fl_head_action:
                startActivity(new Intent(this, NewProblemsActivity.class));
                break;
        }
    }


}
